init('CommandChain');
(function(){
	var CommandChain = function(){
		this.items = [];
		this.index = 0;
	};
	CommandChain.prototype = {
		execute : function(callback){
			if( callback ){
				this.items.push({method:callback, scope:(callback.scope||this), arguments:[]});
			}
			var ctx = this.items[this.index];
			var scope = ctx.scope ? ctx.scope : this;
			ctx.method.apply(scope, ctx.arguments);
		}
		,proceed : function(){
			this.index++;
			if( this.index < this.items.length )
				this.execute();
		}
		,next : function(){
			var scope = this;
			return (function(){
				scope.proceed();
			});
		}
		,add : function(){
			if( arguments.length == 1 ){
				this.items.push(arguments[0]);
			}else{
				var ctx = {method:arguments[0], scope:(arguments[2]||this), arguments:arguments[1]};
				this.items.push(ctx);
			};
			return this;
		}
		,invoke : function(){
			this.add.apply(this, arguments);
		}
		,create : function(){
			var chain = new CommandChain();
			return chain;
		}
	}

	exports.create = function(){
		return new CommandChain();
	}
})();